import logging
import requests
from wxauto import WeChat
import keyboard
import sys
import tkinter as tk
from tkinter import messagebox
from pynput.mouse import Listener

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 初始化微信客户端
wx = WeChat()

# DeepSeek API 配置
DEEPSEEK_API_KEY = "sk-9f5032eb91e942ee8b74219a6a8d9439"  # 你的 DeepSeek API 密钥
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"


def get_deepseek_response(msg):
    """调用 DeepSeek API 获取回复"""
    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json"
    }
    data = {
        "model": "deepseek-chat",  # 使用的模型
        "messages": [{"role": "user", "content": msg}],  # 用户消息
        "temperature": 0.7  # 控制回复的随机性
    }
    try:
        response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data)
        response.raise_for_status()  # 检查请求是否成功
        return response.json()['choices'][0]['message']['content']  # 提取回复内容
    except Exception as e:
        logging.error(f"API 调用失败: {str(e)}")
        return "抱歉，我现在无法处理这个消息。"  # 失败时返回默认回复

logging.info("wpenghui")
logging.info("程序已开启请不要动电脑")
logging.info("关闭程序: Ctrl+K关闭程序")
logging.info("防刷屏: 每回复一次信息后程序会自动打开文件传输助手")
logging.info("防抖: 程序检测到鼠标移动后会停止程序，若5秒内没有任何操作将继续运行 ")

# 定义一个停止标志
stop_flag = False


def stop_program():
    global stop_flag
    stop_flag = True
    logging.info("程序即将停止...")


# 监听 Ctrl + K 组合键
keyboard.add_hotkey('ctrl+k', stop_program)

# 鼠标移动标志
mouse_moved = False


def on_move(x, y):
    global mouse_moved
    mouse_moved = True


# 启动鼠标监听线程
mouse_listener = Listener(on_move=on_move)
mouse_listener.start()


def show_dialog():
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口
    result = None

    def close_dialog():
        nonlocal result
        root.destroy()

    def handle_yes():
        nonlocal result
        result = 'yes'
        root.destroy()

    def handle_close():
        global stop_flag
        stop_flag = True
        root.destroy()

    # 创建提示对话框
    top = tk.Toplevel(root)
    top.title("是否要自行回复")
    label = tk.Label(top, text="检测到你移动了鼠标，是否需要自行回复？"
                               "5秒后关闭此窗口继续，运行脚本")
    label.pack(padx=20, pady=20)
    yes_button = tk.Button(top, text="是", command=handle_yes)
    yes_button.pack(side=tk.LEFT, padx=10)
    no_button = tk.Button(top, text="否", command=close_dialog)
    no_button.pack(side=tk.LEFT, padx=10)
    close_button = tk.Button(top, text="直接关闭", command=handle_close)
    close_button.pack(side=tk.LEFT, padx=10)

    # 设置 5 秒后自动关闭对话框
    top.after(5000, close_dialog)

    root.mainloop()

    if result == 'yes':
        # 显示继续对话框
        root = tk.Tk()
        root.withdraw()
        messagebox.showinfo("点击按钮继续运行脚本", "继续")
        root.destroy()

# 定义需要跳过的发送者数组
skip_senders = ['肚笨猪']  # 可以根据需要添加更多发送者

# 主循环
while not stop_flag:
    if mouse_moved:
        mouse_moved = False
        show_dialog()

    msgs = wx.GetAllNewMessage()  # 获取所有新消息
    if msgs:
        for sender, message_list in msgs.items():
            if sender in skip_senders:  # 跳过特定发送者
                logging.info(f"跳过来自 {sender} 的消息")
                continue

            for msg in message_list:
                # 提取消息内容（确保是纯文本）
                if hasattr(msg, 'content'):  # 检查消息是否有 content 属性
                    msg_content = msg.content
                else:
                    msg_content = str(msg)  # 如果无法提取，直接转换为字符串

                logging.info(f"收到来自 {sender} 的消息: {msg_content}")
                reply_content = get_deepseek_response(msg_content)  # 调用 DeepSeek API 获取回复
                wx.SendMsg(reply_content, sender)  # 发送回复
                logging.info(f"已回复 {sender}: {reply_content}")

                # 切换回文件传输助手，防止消息干扰
                who = '文件传输助手'
                wx.ChatWith(who=who)
                break  # 每次只处理第一条消息
            break  # 每次只处理一个聊天
    else:
        # 没有新消息时切换到文件传输助手
        who = '文件传输助手'
        wx.ChatWith(who=who)

# 程序停止后释放键盘监听
keyboard.unhook_all()
mouse_listener.stop()
sys.exit(0)

